package ace.cmp.spring.graphql.test.test.core.repository.impl;

import ace.cmp.spring.graphql.test.test.core.model.Book;
import ace.cmp.spring.graphql.test.test.core.repository.BookRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/8/22 17:04
 */
@Component
public class BookRepositoryImpl implements BookRepository {

  private static List<Book> books;

  static {
    Book book1 = new Book(1L, "GraphQL Overview", 100L, 1L);
    Book book2 = new Book(2L, "Spring Overview", 100L, 2L);

    books = List.of(book1, book2, new Book(3L, "Spring Overview3", 100L, 100L));
  }

  @Override
  public List<Book> getAll() {
    return books;
  }

  @Override
  public List<Book> getByIdIn(List<Long> ids) {
    List<Book> result = new ArrayList<>();
    for (Book book : books) {
      if (ids.contains(book.getId())) {
        result.add(book);
      }
    }
    return result;
  }

  @Override
  public Book getById(Long id) {
    for (Book book : books) {
      if (book.getId() == id) return book;
    }
    return null;
  }

  @Override
  public Book modify(Long id, String title) {
    Book book = getById(id);
    if (book != null) {
      book.setTitle(title);
    }
    return book;
  }
}
